package JDBCDemo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
    API:Connection
*/
public class Demo02_connection {

    public static void main(String[] args) throws Exception {
        //1.注册驱动
        //Class.forName("com.mysql.cj.jdbc.Driver");

        //2.获取连接
        String url = "jdbc:mysql:///mytest";
        String username = "root";
        String password = "123456";
        Connection con = DriverManager.getConnection(url, username, password);

        //3.定义SQL语句
        String sql1 = "update account set money = 3000 where name = '张三'";
        String sql2 = "update account set money = 3000 where name = '李四'";

        //4.获取执行sql的对象 Statement
        Statement stmt = con.createStatement();

        //5.执行sql
        try {
            //开启事务
            con.setAutoCommit(false);

            int count1 = stmt.executeUpdate(sql1); //返回影响函数
            System.out.println(count1);

            int count2 = stmt.executeUpdate(sql2); //返回影响函数
            System.out.println(count2);

            //提交事务
            con.commit();
        } catch (Exception e) {
            //出现异常回滚事务
            con.rollback();
            e.printStackTrace();
        }


        //释放资源
        stmt.close();
        con.close();
    }
}
